package com.fengye.algorithms.leecode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author fengye
 * @Date 2023/4/8 9:29
 **/
public class TwoSum01 {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length == 2) {
            return new int[] {0,1};
        }
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        for(int i=0,j=nums.length-1;j>=i;i++,j--) {
            if(nums[i] + nums[j] == target) {
                res[0] = i;
                res[1] = j;
                break;
            }
            int key = target - nums[i];
            if(map.containsKey(key)) {
                int index = map.get(key);
                res[0] = Math.min(i, index);
                res[1] = Math.max(i,index);
                break;
            }
            key = target - nums[j];
            if(map.containsKey(key)) {
                int index = map.get(key);
                res[0] = Math.min(j, index);
                res[1] = Math.max(j,index);
                break;
            }
            map.put(nums[i],i);
            map.put(nums[j],j);
        }
        return res;
    }
}
